package com.ssyx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyx.constant.GlobalConstant;
import com.ssyx.constant.RedisConstant;
import com.ssyx.enums.UserType;
import com.ssyx.enums.user.Leader;
import com.ssyx.enums.user.User;
import com.ssyx.enums.user.UserDelivery;
import com.ssyx.exception.SsyxException;
import com.ssyx.mapper.LeaderMapper;
import com.ssyx.mapper.UserDeliveryMapper;
import com.ssyx.mapper.UserMapper;
import com.ssyx.result.ResultCodeEnum;
import com.ssyx.service.UserService;
import com.ssyx.util.HttpClientUtil;
import com.ssyx.utils.JwtHelper;
import com.ssyx.vo.user.LeaderAddressVo;
import com.ssyx.vo.user.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: ssyx-parent
 * @className: UserServiceImpl
 * @description: 类
 * @data: 2024/3/18 13:55
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
	private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
	@Resource
	private UserDeliveryMapper userDeliveryMapper;
	@Resource
	private LeaderMapper leaderMapper;
	@Resource
	private RedisTemplate<String, Object> redisTemplate;
	
	@Value("${ssyx.wx.app_id}")
	private String appId;
	@Value("${ssyx.wx.app_secret}")
	private String appSecret;
	
	@Override
	public LeaderAddressVo getLeaderAddressVoByUserId(Long userId) {
		UserDelivery userDelivery =
				userDeliveryMapper.selectOne(Wrappers.<UserDelivery>lambdaQuery().eq(UserDelivery::getUserId, userId).eq(UserDelivery::getIsDefault, GlobalConstant.INTEGER_ONE));
		if (userDelivery == null) return null;
		Leader leader = leaderMapper.selectById(userDelivery.getLeaderId());
		LeaderAddressVo leaderAddressVo = new LeaderAddressVo();
		BeanUtils.copyProperties(leader, leaderAddressVo);
		leaderAddressVo.setUserId(userId);
		leaderAddressVo.setLeaderId(leader.getId());
		leaderAddressVo.setLeaderName(leader.getName());
		leaderAddressVo.setLeaderPhone(leader.getPhone());
		leaderAddressVo.setWareId(userDelivery.getWareId());
		leaderAddressVo.setStorePath(leader.getStorePath());
		return leaderAddressVo;
	}
	
	@Override
	public UserLoginVo getUserLoginVo(Long userId) {
		User user = getById(userId);
		UserLoginVo userLoginVo =
				UserLoginVo.builder().nickName(user.getNickName()).userId(userId).photoUrl(user.getPhotoUrl()).openId(null).isNew(user.getIsNew()).build();
		//如果是团长获取当前前团长id与对应的仓库id
		if (user.getUserType().equals(UserType.LEADER.getCode())) {
			Leader leader =
					leaderMapper.selectOne(Wrappers.<Leader>lambdaQuery().eq(Leader::getUserId, userId).eq(Leader::getCheckStatus, GlobalConstant.INTEGER_ONE));
			if (leader != null) {
				userLoginVo.setLeaderId(leader.getId());
			}
		} else {
			//如果是会员获取当前会员对应的仓库id
			UserDelivery userDelivery =
					userDeliveryMapper.selectOne(Wrappers.<UserDelivery>lambdaQuery().eq(UserDelivery::getUserId,
							userId).eq(UserDelivery::getIsDefault, GlobalConstant.INTEGER_ONE));
			if (userDelivery != null) {
				userLoginVo.setLeaderId(userDelivery.getLeaderId());
				userLoginVo.setWareId(userDelivery.getWareId());
			} else {
				userLoginVo.setLeaderId(GlobalConstant.LONG_ONE);
				userLoginVo.setWareId(GlobalConstant.LONG_ONE);
			}
		}
		return userLoginVo;
	}
	
	@Override
	public Map<String, Object> wxLogin(String code) {
		if (StringUtils.isEmpty(code)) {
			log.error("code为空");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
		}
		
		// 创建登录数据集合
		HashMap<String, String> map = new HashMap<>();
		map.put("appid", appId);
		map.put("secret", appSecret);
		map.put("js_code", code);
		map.put("grant_type", "authorization_code");
		String res = HttpClientUtil.doGet(WX_LOGIN, map);
		
		// 解析返回数据
		JSONObject jsonObject = JSON.parseObject(res);
		String openid = (String) jsonObject.get("openid");
		log.info("openid:{}", openid);
		if (openid == null) {
			log.error("openid为空");
			throw new SsyxException(ResultCodeEnum.FAIL);
		}
		User user = getOne(new QueryWrapper<User>().eq("open_id", openid));
		// 如果没有查到用户信息,那么调用微信个人信息获取的接口
		if (user == null) {
			user =
					User.builder().openId(openid).nickName(openid).photoUrl("").userType(UserType.USER.getCode()).isNew(GlobalConstant.INTEGER_ZERO).build();
			save(user);
		}
		LeaderAddressVo leaderAddressVo = getLeaderAddressVoByUserId(user.getId());
		Map<String, Object> mapVo = new HashMap<>();
		mapVo.put("user", user);
		mapVo.put("leaderAddressVo", leaderAddressVo);
		String token = JwtHelper.createToken(user.getId(), user.getNickName());
		mapVo.put("token", token);
		redisTemplate.opsForValue().set(RedisConstant.USER_KEY_PREFIX + user.getId(), token,
				RedisConstant.SKUKEY_TIMEOUT, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(RedisConstant.FEIGNCLIENT, GlobalConstant.VALIDATE,
				RedisConstant.KEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
		redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + user.getId(),
				JSONObject.toJSONString(getUserLoginVo(user.getId())), RedisConstant.INFO_TIMEOUT, TimeUnit.DAYS);
		String s = (String) redisTemplate.opsForValue().get(RedisConstant.FEIGNCLIENT);
		log.info("FeignClient(redis)：{}", s);
		return mapVo;
		
	}
}
